package yingyuehu.sso.service.impl;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import yingyuehu.sso.enums.LoginStatus;
import yingyuehu.sso.po.LoginResult;
import yingyuehu.sso.po.LoginUser;
import yingyuehu.sso.service.LoginService;

import javax.annotation.Resource;

/**
 * @program: SpringBootDemos
 * @description:
 * @author: Kangsen
 * @create: 2022-05-20 10:35
 **/
@Service
@Slf4j
public class LoginServiceImpl implements LoginService {

    //private static RestTemplate restTemplate = new RestTemplate();

    @Resource
    private RestTemplate restTemplate;

    /**
     * 用户登录
     *
     * @param account     用户名
     * @param password    密码
     * @param callbackUrl 用户验证回调
     * @return
     */
    @Override
    public LoginResult login(String account, String password, String callbackUrl) {
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.add("Accept",MediaType.APPLICATION_JSON.toString());
            HttpEntity<String> formEntity = new HttpEntity<>(JSON.toJSONString(
                    LoginUser.builder().account(account).password(password)
            ),headers);
            return restTemplate.postForObject(callbackUrl,formEntity,LoginResult.class);
        } catch (RestClientException e) {
            e.printStackTrace();
            log.error("login error => ",e);
            return LoginResult.builder().loginStatus(LoginStatus.CALLBACK_ERROR).build();
        }
    }
}
